<template>
  <j-modal
    :title="title"
    :width="width"
    :visible="visible"
    :confirmLoading="confirmLoading"
    switchFullscreen
    @ok="handleOk"
    @cancel="handleCancel"
    :destroyOnClose="true"
    cancelText="关闭">
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-form-item label="父级节点" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <j-tree-select
            ref="treeSelect"
            placeholder="无"
            v-decorator="['pid']"
            dict="sys_district,name,id"
            pidField="pid"
            pidValue="0"
            disabled=true
            hasChildField="has_child"
            >
          </j-tree-select>
        </a-form-item>
        <a-form-item label="区划代码" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input v-decorator="['id',{rules: [{required: true, message: '请输入区划代码'},{
              validator: this.validateDistrictCode,
            }]}]" :disabled='!(!model.id)' placeholder="请输入区划代码" ></a-input>
        </a-form-item>
        <a-form-item label="区划名称" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input v-decorator="['name',{rules: [{required: true, message: '请输入区划名称'},{
              validator: this.validateDistrictName,
            }]}]" placeholder="请输入区划名称" ></a-input>
        </a-form-item>
<!--        <a-form-item label="区划排序" :labelCol="labelCol" :wrapperCol="wrapperCol">-->
<!--          <a-input-number v-decorator="['sn']" placeholder="请输入区划排序" style="width: 100%" />-->
<!--        </a-form-item>-->
<!--        <a-form-item label="区划路径" :labelCol="labelCol" :wrapperCol="wrapperCol">-->
<!--          <a-input v-decorator="['path']" placeholder="请输入区划路径" ></a-input>-->
<!--        </a-form-item>-->

      </a-form>
    </a-spin>
  </j-modal>
</template>

<script>

  import { httpAction } from '@/api/manage'
  import pick from 'lodash.pick'
  import { validateDuplicateValue } from '@/utils/util'
  import JTreeSelect from '@/components/ksource/JTreeSelect'
  import {duplicateCheck } from '@/api/api'
  export default {
    name: "SysDistrictModal",
    components: {
      JTreeSelect,
    },
    data () {
      return {
        form: this.$form.createForm(this),
        title:"操作",
        width:800,
        visible: false,
        model: {},
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        disable:{
          type: Boolean,
          default: false
        },
        confirmLoading: false,
        validatorRules: {
        },
        url: {
          add: "/platform/system/sysDistrict/add",
          edit: "/platform/system/sysDistrict/edit",
        },
        expandedRowKeys:[],
        pidField:"pid"

      }
    },
    created () {
    },
    methods: {
      validateDistrictName(rule, value, callback){
        var params = {
          tableName: 'sys_district',
          fieldName: 'name',
          fieldVal: value,
          name: this.name
        };
        duplicateCheck(params).then((res) => {
          if (res.success) {
            callback()
          } else {
            if(value){
              callback("该区划已存在!")
            }else{
              callback("")
            }
          }
        })
      },
      validateDistrictCode(rule, value, callback){
        var params = {
          tableName: 'sys_district',
          fieldName: 'id',
          fieldVal: value,
          dataId: this.id
        };
        duplicateCheck(params).then((res) => {
          if (res.success) {
            callback()
          } else {
            if(value){
              callback("该区划代码已存在!")
            }else{
              callback("")
            }
          }
        })
      },
      add (obj) {
        this.edit(obj);
      },
      edit (record) {
        this.form.resetFields();
        this.model = Object.assign({}, record);
        this.visible = true;
        if(record){
          this.disable.default=true
        }
        this.$nextTick(() => {
          this.form.setFieldsValue(pick(this.model,'id','pid','name'))
        })
      },
      close () {
        this.$emit('close');
        this.visible = false;
      },
      handleOk () {
        const that = this;
        // 触发表单验证
        this.form.validateFields((err, values) => {
          if (!err) {
            that.confirmLoading = true;
            let httpurl = '';
            let method = '';
            if(!this.model.id){
              httpurl+=this.url.add;
              method = 'post';
            }else{
              httpurl+=this.url.edit;
               method = 'put';
            }
            let old_pid = this.model[this.pidField]
            let formData = Object.assign(this.model, values);
            let new_pid = this.model[this.pidField]
            console.log("表单提交数据",formData)
            httpAction(httpurl,formData,method).then((res)=>{
              if(res.success){
                that.$message.success(res.message);
                this.$emit('ok');
              }else{
                that.$message.warning(res.message);
              }
            }).finally(() => {
              that.confirmLoading = false;
              that.close();
            })
          }

        })
      },
      handleCancel () {
        this.close()
      },
      popupCallback(row){
        this.form.setFieldsValue(pick(row,'pid','name'))
      },
      submitSuccess(formData,flag){
        if(!formData.id){
          let treeData = this.$refs.treeSelect.getCurrTreeData()
          this.expandedRowKeys=[]
          this.getExpandKeysByPid(formData[this.pidField],treeData,treeData)
          this.$emit('ok',formData,this.expandedRowKeys.reverse());
        }else{
          this.$emit('ok',formData,flag);
        }
      },
      getExpandKeysByPid(pid,arr,all){
        if(pid && arr && arr.length>0){
          for(let i=0;i<arr.length;i++){
            if(arr[i].key==pid){
              this.expandedRowKeys.push(arr[i].key)
              this.getExpandKeysByPid(arr[i]['parentId'],all,all)
            }else{
              this.getExpandKeysByPid(pid,arr[i].children,all)
            }
          }
        }
      }


    }
  }
</script>